package cn.samir.sudoku.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import cn.samir.sudoku.util.LogUtils;
import cn.samir.sudoku.util.ThreadPoolManager;
import cn.samir.sudoku.util.Utils;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class NetTask implements Runnable {

	public static final int success = 1;
	public static final int fail = 2;
	HashMap<String, Object> params = new HashMap<String, Object>();
	OnNetListener listener = null;
	Context context;
	String url;
	int taskcode;
	boolean isGetMethod = true;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				String m = (String) msg.obj;
				System.out.println(m);
				if (listener != null) {
					listener.onSuccess(m);
				}
			case fail:
				listener.onError(msg.obj + "");
				break;
			default:
				break;
			}
		};
	};

	public NetTask(Context context) {
		this.context = context;
	}

	public NetTask(Context context, OnNetListener listener) {
		this.context = context;
		this.listener = listener;
	}

	public NetTask addParams(HashMap<String, String> param) {
		this.params.putAll(param);
		return this;
	}

	public NetTask url(String url) {
		this.url = url;
		return this;
	}

	public void doGet(OnNetListener listener) {
		this.listener = listener;
		// ThreadPoolManager.getInstance().addTask(this);
		doMethod(listener, true);
	}

	public void doPost(OnNetListener listener) {
		this.listener = listener;
		doMethod(listener, false);
	}

	public void doMethod(OnNetListener listener, boolean isGet) {
		isGetMethod = isGet;
		if (NetWorkHelper.isNetworkAvailable(context)) {
			ThreadPoolManager.getInstance().addTask(this);
		} else {
			if (listener != null) {
				listener.onError("网络未连接");
				return;
			}
		}
	}
	
	public void addRequestCode(int code){
		params.put("requestcode", code);
	}
	
	@Override
	public void run() {
		String method = "POST";
		if (isGetMethod) {
			method = "GET";
		}
		LogUtils.d("NetTask", method + "," + url);
		InputStream in = null;
		StringBuffer sb = null;
		try {
			in = syncStream(url, method, params);
			if (listener != null) {
				listener.onSuccess(in);
			}
			if (in != null) {
				Scanner scanner = new Scanner(in);
				sb = new StringBuffer();
				while (scanner.hasNext()) {
					sb.append(scanner.nextLine());
				}
				in.close();
				scanner.close();
			}

		} catch (IOException e) {
			if (listener != null) {
				Message msg = Message.obtain();
				msg.what = fail;
				msg.obj = e.getLocalizedMessage();
				handler.sendMessage(msg);
			}
			e.printStackTrace();
			handler.sendEmptyMessage(2);
		} finally {

			if (sb != null) {
				Message msg = Message.obtain();
				msg.what = success;
				msg.obj = sb.toString();
				handler.sendMessage(msg);
			} else {
				if (listener != null) {
					listener.onError("返回数据为空");
				}
			}
		}

	}

	public static InputStream syncStream(String url, String method,
			Map<String, Object> params) throws IOException {
		HttpResponse response;
		if (method.equalsIgnoreCase("POST")) {
			HttpPost httppost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				if (params.get(key) != null) {
					formparams.add(new BasicNameValuePair(key, params.get(key)
							.toString()));
				}
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
					"UTF-8");
			httppost.setEntity(entity);
			response = HttpManager.execute(httppost);
			Header[] headers = response.getHeaders("Set-Cookie");
			System.out.println(headers);
		} else {
			if (!url.contains("?")) {
				url += "?";
			} else {
				if (!url.endsWith("&")) {
					url += "&";
				}
			}
			url = url + encodeUrl(params);
			HttpGet httpGet = new HttpGet(url);
			response = HttpManager.execute(httpGet);
		}
		HttpEntity rentity = response.getEntity();
		if (rentity != null) {
			return rentity.getContent();
		}
		return null;
	}

	/**
	 * 获取get时的url
	 * 
	 * @param params
	 * @return
	 */
	public static String encodeUrl(Map<String, Object> params) {
		if (params == null || params.size() == 0)
			return "";
		StringBuilder sb = new StringBuilder();
		for (String key : params.keySet()) {
			if (params.get(key) != null) {
				sb.append(key.trim())
						.append("=")
						.append(URLEncoder.encode((params.get(key).toString())))
						.append("&");
			}
		}
		return sb.toString();
	}
}
